/*
 * Copyright 2013 Glassy Cinema.
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *      http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
package hu.glassy.web.panel.account.edit;

import hu.glassy.core.model.Account;
import hu.glassy.core.service.AccountService;
import hu.glassy.web.auth.ApplicationSession;
import hu.glassy.web.component.common.CustomAjaxSubmitLink;
import hu.glassy.web.component.feedback.CustomFeedbackPanel;
import hu.glassy.web.component.visitor.ErrorMessageFormVisitor;
import hu.glassy.web.panel.common.CustomPanel;
import org.apache.wicket.Component;
import org.apache.wicket.ajax.AjaxRequestTarget;
import org.apache.wicket.ajax.markup.html.form.AjaxSubmitLink;
import org.apache.wicket.markup.html.basic.Label;
import org.apache.wicket.markup.html.form.Form;
import org.apache.wicket.markup.html.form.FormComponent;
import org.apache.wicket.markup.html.form.PasswordTextField;
import org.apache.wicket.markup.html.form.StatelessForm;
import org.apache.wicket.markup.html.form.TextField;
import org.apache.wicket.markup.html.form.validation.EqualPasswordInputValidator;
import org.apache.wicket.markup.html.panel.EmptyPanel;
import org.apache.wicket.model.CompoundPropertyModel;
import org.apache.wicket.model.IModel;
import org.apache.wicket.model.PropertyModel;
import org.apache.wicket.model.ResourceModel;
import org.apache.wicket.spring.injection.annot.SpringBean;
import org.apache.wicket.validation.IValidatable;
import org.apache.wicket.validation.IValidator;
import org.apache.wicket.validation.ValidationError;
import org.apache.wicket.validation.validator.EmailAddressValidator;
import org.apache.wicket.validation.validator.StringValidator;

/**
 * Felhasználói adatok bevitelére szolgáló panel
 *
 * @author molnar.alexander@sonrisa.hu
 */
public abstract class AccountDataInputPanel extends CustomPanel<Account>
{

  private static final long serialVersionUID = 1479353085489770242L;

  @SpringBean
  private AccountService accountService;

  /**
   * Konstruktor
   *
   * @param id
   * @param model
   */
  public AccountDataInputPanel(final String id, final IModel<Account> model)
  {
    super(id);

    setDefaultModel(new CompoundPropertyModel<Account>(model));

    Label emailWarning = new Label("emailWarning", getString("account.edit.warning"));
    emailWarning.setVisible(accountService.isEmailActivationRequired());
    add(emailWarning);

    final Form<Account> form = new StatelessForm<Account>("inputForm");
    form.add(new CustomFeedbackPanel("panelFeedback"));

    addFormComponents(form);

    form.visitChildren(new ErrorMessageFormVisitor<String>());
    add(form);

    add(getFooter("footer"));
  }

  private void addFormComponents(final Form<Account> form)
  {
    form.add(generateEmailInput());
    form.add(generateNameInput());
    FormComponent password = generatePasswordInput();
    form.add(password);
    FormComponent cpassword = generateConfirmInput();
    form.add(cpassword);
    form.add(new EqualPasswordInputValidator(password, cpassword));

    form.add(generateSubmitButton());
  }

  private Component generateSubmitButton()
  {
    final AjaxSubmitLink button = new CustomAjaxSubmitLink("submit")
    {
      private static final long serialVersionUID = 8775028623062298638L;

      @Override
      protected void onSubmit(final AjaxRequestTarget target, final Form<?> form)
      {
        super.onSubmit(target, form);

        onFormSubmit(target, AccountDataInputPanel.this.getmainModel());
      }
    };
    return button;
  }

  private FormComponent<String> generateEmailInput()
  {
    FormComponent<String> emailField = new TextField<String>("email");
    emailField.setRequired(true);
    emailField.add(EmailAddressValidator.getInstance());
    emailField.add(generateEmailValidator());
    emailField.add(StringValidator.maximumLength(Account.EMAIL_LENGTH));
    emailField.setVisible(isEmailInputVisible());
    return emailField;
  }

  private FormComponent<String> generateNameInput()
  {
    final TextField<String> input = new TextField<String>("name");
    input.setRequired(true);
    input.add(StringValidator.maximumLength(Account.NAME_LENGTH));
    input.setVisible(isFirstnameInputVisible());
    return input;
  }

  private FormComponent<String> generatePasswordInput()
  {
    PasswordTextField passwordField = new PasswordTextField("password", new PropertyModel<String>(this, "password"));
    passwordField.setRequired(true);
    passwordField.setResetPassword(false);
    passwordField.setVisible(isPasswordInputVisible());
    return passwordField;
  }

  private FormComponent<String> generateConfirmInput()
  {
    PasswordTextField confirmField = new PasswordTextField("confirmPassword", new PropertyModel<String>(this, "confirm"));
    confirmField.setRequired(true);
    confirmField.setResetPassword(false);
    confirmField.setVisible(isConfirmInputVisible());
    return confirmField;
  }

  private IValidator<String> generateEmailValidator()
  {
    return new IValidator<String>()
    {
      private static final long serialVersionUID = -8522982733849492932L;

      public void validate(final IValidatable<String> validatable)
      {
        final String email = validatable.getValue();
        if (ApplicationSession.get().isSignedIn())
        {
          final Account current = ApplicationSession.get().getAccount().getObject();
          if (email.equals(current.getEmail()))
          {
            return;
          }
        }

        if (accountService.isEmailAddressInUse(email))
        {
          validatable.error(new ValidationError(getString("registration.error.email.inuse")));
        }
      }
    };
  }

  protected boolean isUsernameInputVisible()
  {
    return true;
  }

  protected boolean isEmailInputVisible()
  {
    return true;
  }

  protected boolean isFirstnameInputVisible()
  {
    return true;
  }

  protected boolean isLastNameInputVisible()
  {
    return true;
  }

  protected boolean isPasswordInputVisible()
  {
    return true;
  }

  protected boolean isConfirmInputVisible()
  {
    return true;
  }

  /**
   * Visszaadja a mentés gomb feliratát
   *
   * @return
   */
  public IModel<String> getButtonLabel()
  {
    return new ResourceModel("input.submit");
  }

  /**
   * A panel alján megjelenő komponenst adja vissza
   *
   * @param componentId
   *
   * @return
   */
  public Component getFooter(final String componentId)
  {
    return new EmptyPanel(componentId);
  }

  /**
   * Akor hívódik meg, ha a form submit-olódik, tehát a validációs feltételeknek
   * megfeleltek a beviteli mezók.
   *
   * @param target
   *               {@link AjaxRequestTarget}
   * @param model
   *               Account
   */
  abstract public void onFormSubmit(final AjaxRequestTarget target, IModel<Account> model);
}
